from Crypto.Cipher import AES
import binascii
from wechatpy.utils import WeChatSigner

APP_KEY = '587F90466100C2AF'
APP_SECRET = '30DCCDD180921492DAB8069DD2D60C85'
IV = '30DCCDD180921492'


class AESCipher(object):
    def __init__(self):
        self.bs = 16
        self.iv = IV
        self.key = APP_KEY

    def encrypt(self, raw):
        raw = self._pad(raw)
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        return binascii.hexlify(cipher.encrypt(raw))

    def decrypt(self, enc):
        enc = binascii.unhexlify(enc)
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        return cipher.decrypt(enc).decode('utf-8').rstrip("\0")

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * '\0'


def get_sign():
    signer = WeChatSigner()
    signer.add_data(APP_SECRET)
    return signer.signature


import json
import logging
from http import client

from data.models import StudentInfo
from django.http import HttpResponseRedirect, HttpResponse

MEDIA_ID = 'gh_2bf620cf5743'
API_KEY = '65363B34687AD246'
API_SECRET = '34B813C0F15AE36CB4B1006D6020BD24'


def get_code(url):
    params = 'http://weixiao.qq.com/apps/school-auth/login?media_id=%s&app_key=%s&redirect_uri=%s' % (
        MEDIA_ID, API_KEY, url)
    return HttpResponseRedirect(params)


def get_info(code):
    body_dict = {
        'app_key': API_KEY,
        'wxcode': code,
        'app_secret': API_SECRET,
    }
    body_str = json.dumps(body_dict)
    headers = {'Content-Type': 'application/json'}
    conn = client.HTTPConnection('weixiao.qq.com', port=80)
    conn.request('POST', '/apps/school-auth/access-token', body=body_str, headers=headers)
    try:
        token = json.loads(conn.getresponse().read().decode('utf-8'))['access_token']
        conn.request('POST', '/apps/school-auth/user-info', body=json.dumps({'token': token}), headers=headers)
        student_id = json.loads(conn.getresponse().read().decode('utf-8'))['card_number']
        conn.close()
        return student_id
    except KeyError:
        return 0


from time import clock


class Timer:
    def __init__(self):
        self.__start__ = 0
        self.__end__ = 0

    def start(self):
        self.__start__ = clock()

    def end(self):
        self.__end__ = clock()

    def timeit(self):
        if self.__end__ < self.__start__:
            return 0
        else:
            return self.__end__ - self.__start__
